<template>
  <view v-if="showing">

    <view>
      <!-- 背景 -->
      <view class="bg-set"></view>
      <!-- 头部 -->
      <view class="titles">
        <text style="font-size: 60rpx; margin-right: 15rpx">{{
          address[0]
        }}</text>
        <text style="font-size: 45rpx">{{ address[1] }}</text>
      </view>
    </view>
    <view class="subject">
      <view class="main">
        <view class="top-box"></view>
        <view class="txt"> {{ address[2] }} </view>
        <view class="user-info" v-if="storeUser.profile">
          <view class="txtlef">
            <view class="iconfont iconyonghu-xianxing"></view>
            <view>姓名:{{ storeUser.profile?.customerName }}</view>
          </view>
          <view class="txtlef">
            <view class="iconfont icondianhua-copy"></view>
            <view>电话:{{ storeUser.profile?.phoneNumber }}</view>
          </view>
        </view>
      </view>

      <view class="content">
        <view class="tab">
          <uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text"
            activeColor="#2979ff" class="tab-nav"></uni-segmented-control>
        </view>
        <!-- 商品区 -->
        <GoodsList class="GoodsListClass" :list="menuItem" :current='current' :restaurantSerials="restaurantSerials"
          v-if="menuItemtype">
        </GoodsList>
      </view>
    </view>
    <!-- 点击弹窗 -->
    <view>
      <!-- 底部导航栏 -->
      <view class="goods-carts">
        <view class="left">
          <uni-badge class="uni-badge-left-margin" :text="goodsSum" absolute="rightTop" size="small">
            <uni-icons type="cart-filled" size="35" color="royalblue" @click="cartBtn"></uni-icons>
          </uni-badge>
          <view>总价￥：{{ goodsTotal }}</view>
        </view>
        <button class="right" @click="placeAnOrder">立即下单</button>
      </view>
      <!-- 购物车 -->
      <uni-popup ref="cartPopup" type="bottom">
        <uni-list :border="true" class="cart">
          <view class="cart-top">
            <view class="left"><text>已选商品</text></view>
            <view class="right" @click="clearCart">
              <uni-icons type="trash" size="22" color="royalblue"></uni-icons>
              <view>清空</view>
            </view>
          </view>
          <scroll-view :scroll-y="true" :scroll-with-animation="true" class="cart-box">
            <view v-for="(item, index2) in storeCart.cart" :key="index2">
              <view v-if="storeCart.cart[index2].goodsInfo.length > 0">{{ item.orderCategoryName }}
                <uni-list-chat v-for="(it, index) in item.goodsInfo" :key="index"
                  :title="it.foodName || it.foodPackageName"
                  :avatar="!it.imgPath ? 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg' : ('https://api.victorick.com:8222/' + it.imgPath)"
                  :note="'￥' + it.defaultPriceStr + '份'" badge-positon="left">

                  <view class="number_box">
                    <view class="dot" @click="twobindChange(false, it, index2, index)">
                      -
                    </view>
                    <view class="txt">
                      {{ it.num }}
                    </view>
                    <view class="dot" @click="twobindChange(true, it, index2, index)">
                      +
                    </view>
                  </view>

                </uni-list-chat>
              </view>
            </view>
            <view class="cart-empty" v-if="!storeCart.cart || !storeCart.cart.length > 0">购物车为空</view>
          </scroll-view>
        </uni-list>
        <!-- <view class="box"></view> -->
      </uni-popup>
    </view>

  </view>
  <view v-else class="noData">暂无数据</view>
  <!-- 军人身份提示框 -->
  <uni-popup ref="infoDialog" type="dialog">
    <uni-popup-dialog ref="inputClose" title="温馨提示" placeholder="请输入内容" @confirm="dialogConfirm" type="info"
      confirmText="确定">
      <template #default>
        <view style="display: flex;flex-direction: column;justify-content: center;">
          <text>军人套餐一天内下单三餐只算一单的费用</text>
          <text style="margin: 10rpx 0;">报销在收费处申请</text>
          <text>提示余额不足请前往收费处充值登记</text>
        </view>
      </template>
    </uni-popup-dialog>
  </uni-popup>
</template>
<script setup>
import { ref, computed, nextTick } from "vue";
import { onLoad, onShow} from "@dcloudio/uni-app";
// import NP from 'number-precision'
import GoodsList from './goodsList.vue'
import { http } from "../../utils/http";
import { Decimal } from 'decimal.js'
import { timeToTimestamp, timestampToTime } from '../../utils/data'
import { useCartStore, useMemberStore, useMenuStore } from '../../stores';
import { debounce, debounceFn } from '../../utils/tool'

// ------------------------------
const restaurantSerials = ref('')
const infoDialog = ref()//军人身份提示框
const endTime = ref()//餐厅结束时间
onLoad(async (e) => {
  const storeCart = useCartStore()
  const storeUser = useMemberStore()
  endTime.value = e.endTime
  // 军人身份下获取历史订单
  if (storeUser.profile.customerClassFlag == 1) {
    nextTick(() => infoDialog.value.open())
  }
  storeCart.cart = []
  storeCart.cartNew = []
  storeCart.cartObj.restaurantSerials = e.restaurantSerials
  storeCart.cartObj.orderDate = e.date
  restaurantSerials.value = e.restaurantSerials
  getWXMenu(e.restaurantSerials, e.date)
  // 判断只能在三级地址下才能下单
  if (address[1] == "null" || address[2] == "null") {
    uni.showModal({
      content: '当前地址不允许点餐，请重新扫描二维码',
      confirmText: "确认",
      showCancel: false,
      complete: function (res) {
        console.log(res);
        //点击“确认”时打开设置页面
        wx.navigateBack({
          delta: 1
        })
      },
    });
  }
})
onShow(() => {
  const storeUser = useMemberStore()
  // 军人身份下获取历史订单
  if (storeUser.profile.customerClassFlag == 1) {
    getFoodOrders()
  }
})

// 弹框点击确认
const dialogConfirm = () => {
  console.log('点击了确定');
  infoDialog.value.close()
}
const storeUser = useMemberStore() || []
const storeCart = useCartStore()
const menuList = ref([])//菜单完整信息
const menuItem = ref([])//餐别对应菜单详情
const items = ref([]);
const orderList = ref([])//历史订单数据
const ordernum = ref()
const menuItemtype = ref(false);
let current = ref(0);
let clearTime=''//营业时间到了，强制性退出页面-定时器
const showing = ref(false)
const address = storeUser.profile.addressTxt.split(' ')//页面渲染地址数据
// 获取历史订单
const getFoodOrders = async () => {
  const storeCart = useCartStore()
  const res = await http({
    url: '/GetFoodOrders',
    method: 'post',
    data: {
      ...storeUser.requestData,
      data: {
        "orderNo": [
          ""
        ],
        "addressSerials": [

        ],
        "addressId": [

        ],
        "addressName": '',
        "orderStatusCode": [

        ],
        "orderCategorySerials": [],
        "restaurantSerials": [

        ],
        "restaurantName": '',
        "createBeginTime": "",
        "createEndTime": ""
      }
    }
  })
  // 进入点餐页面获取历史订单，如果有数据地情况下
  if (res.errcode == 0 && res.data?.length > 0) {
    const restime = res.restime.split(" ")[0].split("/")
    const formattedDate = `${restime[0]}-${restime[1].padStart(2, "0")}-${restime[2].padStart(2, "0")}`;
    const kk = res.data.map(({ foodpackagelist, orderStatusCode, createTime }) => ({ foodpackagelist, orderStatusCode, createTime }))
    const hh = kk.filter(item => item.orderStatusCode == 2 || item.orderStatusCode == 5)//获取状态为已接单||已完成历史记录
    const end = hh.filter(item => item.createTime?.split(" ")[0] == formattedDate.split(" ")[0])//当天下单下的订单数据
    const end1 = end.map(({ foodpackagelist }) => ({ foodpackagelist: foodpackagelist?.filter(it => it.sameTypeFreeSign == 1) }))//查询到的免费订单
    const ss = []
    end1.forEach(item => ss.push(item.foodpackagelist[0]))
    orderList.value = end1
    storeCart.cartObj.orderList = ss

  }
}
// 获取菜单列表
const getWXMenu = async (restaurantSerials, menuDate) => {
  const { data, restime } = await http({
    url: '/GetWXMenu',
    method: 'post',
    data: {
      ...storeUser.requestData,
      data: {
        restaurantSerials,
        menuDate
      }
    }
  })
  let time=timeToTimestamp(endTime.value)-timeToTimestamp(restime)
  clearTime= setTimeout(()=>{
    setTimeout(()=>{
      uni.showToast({
            title: '餐厅营业结束，明天再来吧',
            icon: 'none',
            duration: 2000
          })
    },200)
   uni.navigateBack({delta:2})
  },time)
  showing.value = data ? true : false
  if (!showing.value) return
  if (data[0])
    menuList.value = data[0]
  menuItem.value = menuList.value.ordercategorylist[0]
  items.value = menuList.value.ordercategorylist.map(item => item.orderCategoryName)
  menuItemtype.value = true
  // -----------------------------
  // 获取菜单里面所有的套餐

  // ---------------------------
}
// 点击餐别切换菜单
let onClickItem = (e) => {
  current.value = e.currentIndex
  menuItem.value = JSON.parse(JSON.stringify(menuList.value.ordercategorylist[current.value]))
};
// 商品数量
let goodsSum = computed(() => {
  let cartArr = storeCart.cartNew;
  if (cartArr.length > 0) {
    return cartArr.reduce((prev, cur, index, arr) => {

      prev = prev + cur.goodsInfo.num
      storeCart.cartObj.goodsNum = prev
      return prev
    }, 0)
  } else {
    storeCart.cartObj.goodsNum = 0
    return 0
  }
})
// 商品总价
let goodsTotal = computed(() => {
  const storeMember = useMemberStore()
  let cartArr = storeCart.cartNew;
  if (cartArr.length > 0) {
    // 1.军人分开点的情况下，查询到当天历史订单有无免费订单，如果有则显示0.00
    if (storeMember.profile.customerClassFlag == 1) {
      if (storeCart.cartObj.orderList.length > 0) {
        storeCart.cartObj.totalMoney = 0.00
        return 0.00
      } else {
        // 2.军人身份一日三餐同时点，购物车只显示84.85
        const freeNum = cartArr.filter(item => item.sameTypeFreeSign == 1)
        if (freeNum.length > 0) {
          storeCart.cartObj.totalMoney = freeNum[0].goodsInfo.defaultPriceStr
          return storeCart.cartObj.totalMoney
        }
      }

    }

    return cartArr.reduce((prev, cur) => {
      // return NP.plus(prev,NP.times(cur.num,Number(cur.price)))
      storeCart.cartObj.totalMoney = new Decimal(prev).add(new Decimal(cur.goodsInfo.num).mul(new Decimal(cur.goodsInfo.defaultPriceStr)))
      return new Decimal(prev).add(new Decimal(cur.goodsInfo.num).mul(new Decimal(cur.goodsInfo.defaultPriceStr)))
    }, 0)
  } else {
    storeCart.cartObj.totalMoney = 0.00
    return 0.00
  }

})
// 购物车
const cartPopup = ref();
const cartBtn = () => {
  const storeCart = useCartStore()
  // 点击购物车先取本地的数据
  cartPopup.value.open();
}
const clearCart = () => {//清空购物车
  if (storeCart.cartNew && storeCart.cartNew.length > 0) {
    uni.showModal({
      title: '确定清空购物车？',
      success: function (res) {
        if (res.confirm) {
          storeCart.clearCart()
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  }

}

let twobindChange = (type, it, index2, index) => {
  if (type) {
    it.num += 1
  } else {
    it.num -= 1

  }
  if (it.num == 0) {
    // 同步删除购物车数据
    storeCart.cart[index2].goodsInfo.splice(index, 1)
    if (storeCart.cart[index2].goodsInfo.length == 0) {
      storeCart.cart.splice(index2, 1)
    }
    storeCart.cartNew.splice(storeCart.cartNew.findIndex(item => item.goodsInfo.foodId == it.foodId), 1)
  }
}
const requestAmount = ref({
  orderNo: '',
  restaurantSerials: "",
  orderDate: "",
  defaultTotalAmount: "",
  customerId: "",
  foodpackagelist: [
  ],
  foodlist: [
  ]
})
// 请求体相同属性
const requestSomeObj = ref({
  status: "1",
  createTime: "",
  cancelTime: "",
  lastEditTime: "",
  lastEditor: "",
  chargeBackReqTime: "",
  chargeBackReqUserId: "",
  chargeBackConfirmTime: "",
  chargeBackConfirmAdminId: "",
  returnNumber: ""
})
// 计算商品总价
const getCalculateAmount = async (e, type, requestObj) => {
  const storeCart = useCartStore()
  storeCart.cartObj.paymsg = []
  const { data, errcode, errmsg, restime } = await http({
    url: '/GetCalculateAmount',
    method: 'post',
    data: {
      ...storeUser.requestData,
      data: requestObj
    }
  })
  if (errcode != 0) {
    // const str = errmsg.substring(4)
    uni.showToast({
      title: errmsg,
      icon: "none",
      duration: 2000,
    });
    return false
  }
  data.forEach((it) => {
    // todo餐补余额
    if (it.paymentAmount > 0) {
      storeCart.cartObj.paymsg.push({
        ...it,
        orderNo: it.orderNo
      })
    }
  })
  if (type) {
    clearTimeout(clearTime)
    uni.navigateTo({
      url: `/pages/order_confirm/order_confirm?request=${JSON.stringify(requestObj)}&time=${endTime.value}&orderList=${JSON.stringify(ordernum.value)}`
    })
  }
}
// 创建订单
const getOrderFn = async () => {
  const storeUser = useMemberStore()
  const storeCart = useCartStore()
  const { data, restime } = await http({
    url: '/GetNewFoodOrderNo',
    method: 'post',
    data: { ...storeUser.requestData }
  })
  console.log(data,'datadata');
    storeCart.cartObj.orderNo.push({ orderNo: data.orderNo, restime })
    return storeCart.cartObj.orderNo
}
// 下单
const requestObj = ref([])
const placeAnOrder = async () => {
  requestObj.value = []
  const storeCart = useCartStore()
  const storeUser = useMemberStore()
  // -------------------------------------------------
  // -------------------------------------------------
  if (storeCart.cartNew.length > 0) {

    uni.showLoading({
      title: '加载中',
      mask: true
    })
   
    // 创建订单
    for (let i = 0; i < storeCart.cart.length; i++) {
      ordernum.value = await getOrderFn()
    }
      // 计算总结请求体
    // 分别计算出餐别下订单金额
    for (let i = 0; i < storeCart.cart.length; i++) {
      const obj = storeCart.cart[i];
      let sum = 0;
      for (let j = 0; j < obj.goodsInfo.length; j++) {
        const item = obj.goodsInfo[j];
        sum += ((item.defaultPriceStr * 100) / 100 * (item.num * 100) / 100);
      }
      obj.sum = sum
    }
    const result = storeCart.cart.map((obj, index) => {
      // 将 获取到的订单数据中的属性添加到每个对象的 order 属性上
      return { ...obj, order: ordernum.value[index] };
    });
    for (let i = 0; i < result.length; i++) {

      const item = result[i]

      const kk = []
      const hh = []
      let index = -1
      item.goodsInfo.forEach((it) => {
        if (it.foodSerials) {
          kk.push({
            foodSerials: it.foodSerials, foodName: it.foodName, number: it.num.toString(), defaultPrice: it.defaultPriceStr, ...requestSomeObj.value, imgPath: ''
          })
        } else {
          index += 1
          hh.push({
            foodPackageSerials: it.foodPackageSerials,
            foodPackageName: it.foodPackageName,
            foodPackageTypeSerials: it.foodPackageTypeSerials,
            foodPackageTypeName: it.foodPackageTypeName,
            number: it.num.toString(),
            defaultPrice: it.defaultPriceStr,
            imgPath: '',
            sameTypeFreeSign: item.sameTypeFreeSign,
            foodlist: [],
            ...requestSomeObj.value
          })
          it.foodlist.forEach(row => {
            hh[index].foodlist.push(
              {
                foodSerials: row.foodSerials,
                foodName: row.foodName,
                number: '',
                defaultPrice: '',
                imgPath: '',
                ...requestSomeObj.value
              }
            )
          })
        }
      })
      requestAmount.value = ({
        orderNo: item.order.orderNo,
        restaurantSerials: storeCart.cartObj.restaurantSerials,
        orderDate: storeCart.cartObj.orderDate,
        defaultTotalAmount: item.sum.toFixed(2).toString(),
        customerId: storeUser.requestData.customerId,
        foodpackagelist: hh,
        foodlist: kk
      })
      requestObj.value.push({ ...requestAmount.value, orderCategoryName: item.orderCategoryName, restime: item.order.restime, orderCategorySerials: item.orderCategorySerials })
      console.log(requestObj.value, 'requestObj.value');
      if (result.length - 1 == i) {
        getCalculateAmount(requestAmount.value, i == result.length - 1, requestObj.value)
        // debounce( getCalculateAmount(requestAmount.value, i == result.length - 1, requestObj.value),200)
      }
      storeCart.cartObj.orderNo = []
    }
  
  // debugger
  } else {
    uni.showToast({ title: '请选择商品下单', icon: 'none' })
  }
}
</script>

<style scoped lang="scss">
.bg-set {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: #37b3fb;
  z-index: -1;
}

.box {
  text-align: center;
  margin: 20rpx auto;
  margin-top: 0;

}

.number_box {
  display: flex;
  align-items: center;
  height: 100%;

  .dot {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    height: 40rpx;
    width: 40rpx;
    font-size: 40rpx;
    border-radius: 50rpx;
    background-color: #2979ff;
  }

  .txt {
    font-size: 40rpx;
    margin: 0 20rpx;
  }
}

.titles {
  width: 100%;
  height: 100rpx;
  text-align: center;
  color: #fff;
}

.subject {
  overflow: hidden;
}

.main {
  width: 100%;
  border-radius: 40rpx 40rpx 0 0;
  background-color: #fff;
  box-sizing: border-box;
  padding: 10rpx 20rpx;

  .user-info {
    display: flex;
    justify-content: space-between;
    padding: 3rpx;

    .txtlef {
      flex: 1;
      display: flex;
      font-size: 30rpx;
      align-items: center;
      color: #5b5a5a;

      .icon {
        width: 35rpx;
        height: 35rpx;
        margin-right: 2rpx;
      }
    }
  }

  .txt {
    flex: 1;
    font-weight: 700;
    font-size: 40rpx;
    margin-bottom: 10rpx;
    text-align: center;
    // border-left: 20rpx solid #37b3fb;
  }

  .top-box {
    width: 100rpx;
    height: 20rpx;
    margin: 0 auto;
    border-radius: 18rpx 18rpx;
    margin-bottom: 10rpx;
    background-color: #eee;
  }
}

.content {
  .tab {
    height: 70rpx;
    border-top: 2rpx solid #ddd;
    background-color: #fff;
    padding-bottom: 8rpx;
    font-size: 32rpx;
  }

  .GoodsListClass {
    height: calc(100% - 70rpx);
  }
}

.goods-carts {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 0;
  height: calc(100rpx + env(safe-area-inset-bottom) / 2);
  padding-bottom: calc(env(safe-area-inset-bottom) / 2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx;
  background-color: #fff;
  z-index: 9;
  box-shadow: -5rpx -4rpx 5px 0rpx rgba(0, 0, 0, 0.2);

  .left {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 40rpx;
  }

  .right {
    flex: 1;
    height: 85rpx;
    margin-right: 30rpx;
    line-height: 85rpx;
    text-align: center;
    color: #fff;
    background: linear-gradient(90deg, #2979ff, #37b3fb);
  }
}

::v-deep .uni-numbox__minus,
::v-deep .uni-numbox-btns {
  font-size: 18rpx;
  border-radius: 50%;
  width: 32rpx;
  height: 32rpx;
  padding: 3rpx;
  margin-top: 7rpx;
}

::v-deep .uni-numbox__value {
  background-color: transparent !important;
  color: #000 !important;
  //background-color: #cf4444 !important;
  width: 32rpx;
  height: 32rpx;
}

::v-deep .cart .uni-list-chat__content .uni-list-chat__content-note {
  color: #000 !important;
  font-size: 24rpx !important;
}

//底部占位条
.box {
  width: 100%;
  height: 120rpx;
  background-color: #fff;
}

//购物车
.cart {
  .cart-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    padding: 15rpx;
    border: 1px solid #ddd;

    .left {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &::before {
        width: 16rpx;
        height: 40rpx;
        border-radius: 8rpx;
        content: "";
        background-color: #37b3fb;
        display: inline-block;
        margin-right: 10rpx;
      }
    }

    .right {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .cart-box {

    max-height: 600rpx;
    overflow: scroll;

    .slot-number {
      margin-top: 20rpx;
    }

    .cart-empty {
      padding: 18rpx;
      text-align: center;
    }
  }
}

.noData {
  text-align: center;
  margin: 20rpx auto;
}
</style>
